package com.guo.hui.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.guo.hui.dao.blog.TpLinksMapper;
import com.guo.hui.model.blog.TpLinks;
import com.guo.hui.model.shiro.TpUser;
import com.guo.hui.util.UtilJson;

@Controller
@RequestMapping("/link")
public class LinkController extends BaseController{
	
	@Autowired
	private TpLinksMapper linkDao;
	
	@RequestMapping("/web")
	public String web(Model mm) {
		TpUser user =  getUserInfo();
		Map<String, Object> map = new HashMap<>();
		if(!StringUtils.isEmpty(user.getUsername())&&!"admin".equals(user.getUsername())){
			map.put("username", user.getUsername());
		}
		List<TpLinks> listLink = linkDao.selectByMap(map);
		mm.addAttribute("links", listLink);
		return "blog/link/web";
	}

	@RequestMapping("/index")
	public String index(Model mm) {
		return "blog/link/index";
	}
	
	@RequestMapping("/linkadd")
	public String dictadd() {
		return "blog/link/add";
	}

	@ResponseBody
	@RequestMapping("/linksave")
	public String linksave(@RequestParam String link) {
		TpLinks tp = (TpLinks) UtilJson.fromJson(link, TpLinks.class);
		TpUser user =  getUserInfo();
		tp.setUsername(user.getUsername());
		linkDao.insert(tp);
		return "ok";
	}

	@ResponseBody
	@RequestMapping("/linkdata")
	public String dictdata(Model mm) {
		TpUser user =  getUserInfo();
		Map<String, Object> map = new HashMap<>();
		if(!StringUtils.isEmpty(user.getUsername())&&!"admin".equals(user.getUsername())){
			map.put("username", user.getUsername());
		}
		List<TpLinks> listLink = linkDao.selectByMap(map);
		return UtilJson.toJson(listLink);
	}

	@ResponseBody
	@RequestMapping("/linkdelete")
	public String dictdelete(@RequestParam int id) {
		linkDao.deleteById(id);
		return "ok";
	}

	@RequestMapping("/update")
	public String update(Model mm, @RequestParam int id) {
		TpLinks tp = linkDao.selectById(id);
		mm.addAttribute("tp", tp);
		return "blog/link/update";
	}

	@ResponseBody
	@RequestMapping("/linkupdate")
	public String linkupdate(@RequestParam String tp) {
		TpLinks link = (TpLinks) UtilJson.fromJson(tp, TpLinks.class);
		linkDao.update(link);
		return "ok";
	}


}
